package com.zxt.recruit.service;


import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxt.recruit.model.SysElementUserinfo;
import com.zxt.recruit.service.impl.SysElementUserinfoServiceImpl;
import com.zxt.recruit.util.UUIDGeneratorUtil;
import com.zxt.recruit.util.UserRolesUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * UserDetailsService的实现类
 *
 * @author 24862
 */
@Service
@Slf4j
public class AuthUserDetailService implements UserDetailsService {


    @Resource
    SysElementUserinfoServiceImpl userInfoService;

    @Autowired
    private UserRolesUtil userRolesUtil;

    /**
     * 这一层必须采用username+password
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null) {
            throw new UsernameNotFoundException("用户名不能为空");
        }
        try {
            SysElementUserinfo user = userInfoService.getOne(new QueryWrapper<SysElementUserinfo>()
                    .eq("username", username)
                    .eq("is_enabled",1)
                    .eq("is_deleted",0)
            );
            user.setRoles(userRolesUtil.userRolesGet(user.getUserPk()).toString());
            log.info(user.toString());
            log.info(user.getAuthorities().toString());
            return user;
        }catch (UsernameNotFoundException e){
            throw new UsernameNotFoundException("username password state error");
        }
    }

    /**
     * 在之前要进行一次邮箱的注册数量的统计，如果大于某个数量，那么就返回相对应的账号，并决定是否进行删除操作。
     * 该策略后续*****可能*******考虑
     * @param user
     * @return
     */
    public SysElementUserinfo insertUser(SysElementUserinfo user) {
        try {
            String userId = UUIDGeneratorUtil.generateRandomUUID();
            user.setUserPk(userId);
            user.setInputTime(LocalDateTimeUtil.now());
            if (userInfoService.save(user)) {
                return user;
            }
            return null;
        } catch (Exception e) {
            log.info(e.getMessage());
            return null;
        }
    }
}
